<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\exception\BackAuthException;
use app\common\util\CacheKey;
use Firebase\JWT\JWT;
use think\App;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Env;

class Base extends BaseController
{
    protected $admin;
    /**
     * dev环境变量
     * @var string
     */
    protected $environDev = 'dev';
    /**
     * 默认管理员id
     * @var int
     */
    protected $defaultAdminId = 1;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $request = \request();
        if ($this->isDev()) {
            $this->admin = Db::table("admin")->where(['id'=>$this->defaultAdminId])->find();
            $this->admin['roles'] = explode(",",$this->admin['roles']);
        } else {
            $jwtKey = env("jwt_key");
            $token = $request->header("Authorization");
            try {
                $payload = JWT::decode($token,$jwtKey, array('HS256'));
                if ($payload) {
                    //检测登录时间 是否过期
                    if ($payload->t != CacheKey::ADMIN) {
                        throw new BackAuthException("没有登录");
                    }
                    if($payload->exp < time()) {
                        throw new BackAuthException("登录过期");
                    }
                    $this->admin = Cache::get(CacheKey::ADMIN."#".$payload->id); //配置的名称应该统一，不然怕出错
                    if (empty($this->admin)) {
                        $this->collectAdminInfo($payload->id, $payload->exp);
                    }
                } else {
                    throw new BackAuthException("没有登录");
                }
            } catch (\Exception $e) {
                throw  new \Exception($e);
            }
        }
    }

    protected function isSuper()
    {
        return in_array('admin', $this->admin['roles']);
    }

    /**
     * 开发环境判断
     * @return bool
     */
    protected function isDev()
    {
        $environ = Env::get('local.environ') ?? 'production';
        return $environ == $this->environDev;
    }

    /**
     * 设置admin信息并缓存
     * @param $adminId
     * @param $expireTime
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function collectAdminInfo($adminId, $expireTime)
    {
        $this->admin = Db::table("admin")->where(['id'=>$adminId])->find();
        $this->admin['roles'] = explode(",",$this->admin['roles']);
        Cache::set(CacheKey::ADMIN."#".$this->admin['id'],$this->admin,($expireTime - time())); //跟登录的时间有效期一样长
    }
}
